package com.koushikdutta.ion;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import com.koushikdutta.ion.bitmap.Transform;

class DefaultTransform implements Transform {
    static final Paint bilinearSamplingPaint = new Paint(2);
    final int resizeHeight;
    final int resizeWidth;
    final ScaleMode scaleMode;

    public DefaultTransform(int width, int height, ScaleMode scaleMode) {
        this.resizeWidth = width;
        this.resizeHeight = height;
        this.scaleMode = scaleMode;
    }

    public Bitmap transform(Bitmap b) {
        Config config = b.getConfig();
        if (config == null) {
            config = Config.ARGB_8888;
        }
        int resizeWidth = this.resizeWidth;
        int resizeHeight = this.resizeHeight;
        if (resizeWidth <= 0) {
            resizeWidth = (int) (((float) resizeHeight) * (((float) b.getWidth()) / ((float) b.getHeight())));
        } else if (resizeHeight <= 0) {
            resizeHeight = (int) (((float) resizeWidth) * (((float) b.getHeight()) / ((float) b.getWidth())));
        }
        RectF destination = new RectF(0.0f, 0.0f, (float) resizeWidth, (float) resizeHeight);
        if (this.scaleMode != ScaleMode.FitXY) {
            float ratio;
            float xratio = ((float) resizeWidth) / ((float) b.getWidth());
            float yratio = ((float) resizeHeight) / ((float) b.getHeight());
            if (this.scaleMode == ScaleMode.CenterCrop) {
                ratio = Math.max(xratio, yratio);
            } else {
                ratio = Math.min(xratio, yratio);
            }
            float transx = (((float) resizeWidth) - (((float) b.getWidth()) * ratio)) / 2.0f;
            float transy = (((float) resizeHeight) - (((float) b.getHeight()) * ratio)) / 2.0f;
            destination.set(transx, transy, ((float) resizeWidth) - transx, ((float) resizeHeight) - transy);
        }
        if (destination.width() == ((float) b.getWidth()) && destination.height() == ((float) b.getHeight()) && destination.top == 0.0f && destination.left == 0.0f) {
            return b;
        }
        Bitmap ret = Bitmap.createBitmap(resizeWidth, resizeHeight, config);
        new Canvas(ret).drawBitmap(b, null, destination, bilinearSamplingPaint);
        return ret;
    }

    public String key() {
        return this.scaleMode.name() + this.resizeWidth + "x" + this.resizeHeight;
    }
}
